import qs from "../../lib/qs/qs";
import to from "../../lib/await-to-js/await-to-js.es5";

import { tabbar_route_map, linkToTabbar } from "../../utils/route.js";
import { API_URL } from "../../api/config.js";
import api from "../../api/api.js";
import http from "../../utils/request.js";
// pages/auth/auth.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},
  async getUserInfo(e) {
    console.log(e.detail);
    const _this = this;
    const { userInfo } = e.detail;

    if (userInfo) {
      const result = await http.login();
      console.log("result", result);
      const { code } = result;

      const data = Object.assign({}, { code }, userInfo);
      const [err, res] = await to(
        http.req({
          url: api.WxAuth,
          method: "POST",
          data
        })
      );

      console.log("err", err);
      console.log("请求结果", res);
      if (err) {
        wx.showModal({
          title: "提示",
          content: `请求用户数据失败${JSON.parse(err)}}`,
          showCancel: false
        });
        return;
      }

      wx.setStorageSync("userInfo", userInfo);
      app.globalData.isAuth = true;

      const { openid } = res;

      if (openid) {
        wx.setStorageSync("token", openid);
        // this.testLoadWasherInfoData();
      } else {
        wx.showModal({
          title: "提示",
          content: "登录失败",
          showCancel: false
        });
      }
    }
    wx.pro.navigateBack({
      delta: 1
    });
  }
});
